﻿using System.Web.Mvc;
using System.Collections.Generic;

using JetBrains.Annotations;

using Orchard;
using Orchard.Security;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using FruitCake.ContactPage.Services;

namespace FruitCake.ContactPage.Drivers
{
    [UsedImplicitly]
    [OrchardFeature("FruitCake.ContactPage")]
    public class ContactPagePageDriver : ContentPartDriver<Models.ContactPagePart>
    {
        private readonly IWorkContextAccessor _workContextAccessor;
        private readonly IContactService _contactService;
        
        public ContactPagePageDriver(
            IWorkContextAccessor workContextAccessor, 
            IContactService contactService)
        {
            _workContextAccessor = workContextAccessor;
            _contactService = contactService;
        }

        public Localizer T { get; set; }

        protected override DriverResult Display(Models.ContactPagePart part, string displayType, dynamic shapeHelper)
        {
            var form = new ViewModels.ContactPageFormViewModel();
            var currentUser = _workContextAccessor.GetContext().CurrentUser;

            if (currentUser != null)
            {
                form.Name = currentUser.UserName;
                form.Mail = currentUser.Email;
            }

            var reasons = PrepareReasons(part);
            var layout = PrepareLayout(part);

            return ContentShape("Parts_FruitCake_ContactPage",
                () => { return shapeHelper.Parts_FruitCake_ContactPage(Form: form, Part: part, Reasons: reasons, Layout: layout); });
        }

        protected override DriverResult Editor(Models.ContactPagePart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_FruitCake_ContactPage_Edit",
                () => shapeHelper.EditorTemplate(TemplateName: "Parts/FruitCake.ContactPage.Edit", Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(Models.ContactPagePart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (!updater.TryUpdateModel(part, Prefix, null, null))
            {
                // ToDo: ...
            }
            else
            {
                if (!part.ValidateReasonRules())
                {
                    updater.AddModelError("ReasonsList", T("Invalid reasons list"));                    
                }
            }
            
            return Editor(part, shapeHelper);
        }

        protected IEnumerable<SelectListItem> PrepareReasons(Models.ContactPagePart part)
        {
            if (!part.IsReasonVisible) return null;

            List<SelectListItem> list = new List<SelectListItem>();

            IEnumerable<Models.ReasonRule> rules = part.GetReasonRules();
            if (rules == null) rules = _contactService.GetDefaultReasons();
 
            foreach (Models.ReasonRule rule in rules)
            {
                SelectListItem item = new SelectListItem()
                {
                    Text = rule.Text,
                    Value = rule.Index
                };

                list.Add(item);
            }

            return list;
        }

        protected ViewModels.FormAspect PrepareLayout(Models.ContactPagePart part)
        {
            return new ViewModels.FormAspect
            {
                TextMaxLength = part.TextMaxLength,
                TextClass = part.TextClass,
                TextRows = part.TextRows > 0 ? part.TextRows.ToString() : "15",
                TextCols = part.TextCols > 0 ? part.TextCols.ToString() : "30",
                InputClass = part.InputClass,
                InputSize = part.InputSize > 0 ? part.InputSize.ToString() : "0"
            };
        }
    }
}